package com.jungle.sp.daily;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedPacket {
    public static List<BigDecimal> divideRedPacket(BigDecimal totalAmount, int n) {
        List<BigDecimal> result = new ArrayList<>();
        Random random = new Random();
        BigDecimal remainAmount = totalAmount;
        for (int i = 0; i < n - 1; i++) {
            // 计算当前的最大可分配金额
            BigDecimal max = remainAmount.divide(BigDecimal.valueOf(n - i), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(2));
            // 生成随机金额
            BigDecimal randomAmount = BigDecimal.valueOf(random.nextDouble()).multiply(max).setScale(2, BigDecimal.ROUND_HALF_UP);
            // 保证随机金额至少为 0.01
            if (randomAmount.compareTo(BigDecimal.valueOf(0.01)) < 0) {
                randomAmount = BigDecimal.valueOf(0.01);
            }
            result.add(randomAmount);
            // 更新剩余金额
            remainAmount = remainAmount.subtract(randomAmount);
        }
        // 最后一个红包分配剩余的所有金额
        result.add(remainAmount.setScale(2, BigDecimal.ROUND_HALF_UP));

        return result;
    }

    public static void main(String[] args) {
        BigDecimal totalAmount = new BigDecimal("100");
        int n = 100;
        List<BigDecimal> redPackets = divideRedPacket(totalAmount, n);
        System.out.println(redPackets);
        BigDecimal reduce = redPackets.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println(reduce);
    }
}
